package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.exception.BaseException;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;
import java.util.Set;

@Slf4j
@Service
public class DishServiceImpl implements DishService {

    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private DishFlavorMapper dishFlavorMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private SetmealDishMapper setmealDishMapper;

    //清理redis缓存
    private void clearCache(String pattern){
        Set keys = redisTemplate.keys(pattern);
        redisTemplate.delete(keys);
    }
    //新增菜品
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void save(DishDTO dishDTO){
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO,dish);
        dish.setStatus(1);
        //插入菜品基础信息(这里会主键回调，之后dish就有id了)
        dishMapper.insert(dish);

        //获取口味信息
        List<DishFlavor> flavors = dishDTO.getFlavors();
        //如果没有口味信息，直接返回
        if(flavors == null || flavors.isEmpty()){
            return;
        }
        //为口味信息设置菜品id
        flavors.forEach(dishFlavor -> dishFlavor.setDishId(dish.getId()));
        //插入菜品口味信息
        dishFlavorMapper.insert(dishDTO);

        //删除缓存
        String key = "dish_" + dish.getCategoryId();
        clearCache(key);
    }

    //分页查询
    @Override
    public PageResult pageList(DishPageQueryDTO dishPageQueryDTO) {
        PageHelper.startPage(dishPageQueryDTO.getPage(),dishPageQueryDTO.getPageSize());
        Page<DishVO> pages = (Page<DishVO>)dishMapper.selectPage(dishPageQueryDTO);
        return new PageResult(pages.getTotal(),pages.getResult());
    }
    //菜品起售和停售
    @Override
    public void changeStatus(Integer status,Long id){
        //停售菜品时如果菜品和起售套餐关联，则不能停售
        if(status.equals(StatusConstant.DISABLE)){
            Integer count = setmealDishMapper.countDishInSetmealOnSale(id);
            if(count > 0){
                throw new BaseException(MessageConstant.DISH_IN_SETMEAL_ON_SALE);
            }
        }

        Dish dish = new Dish();
        dish.setId(id);
        dish.setStatus(status);
        dishMapper.update(dish);

        //删除缓存
        clearCache("dish_*");
    }

    //更新菜品信息
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void update(DishDTO dishDTO){
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO,dish);
        //更新菜品基本信息
        dishMapper.update(dish);
        //根据dishId删除口味信息

        dishFlavorMapper.deleteByDishIds(Arrays.asList(dish.getId()));
        //插入新的口味信息
        dishDTO.getFlavors().forEach(dishFlavor -> dishFlavor.setDishId(dish.getId()));
        dishFlavorMapper.insert(dishDTO);
        //删除缓存
        clearCache("dish_*");
    }

    //根据ids批量删除菜品信息
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteByIds(List<Long> ids) {
        //查询当前setmeal_dish中dish_id为ids中id的数量
        Integer dishCount = setmealDishMapper.countBySetmealId(ids);
        if(dishCount > 0){
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }
        //查询当前ids中起售的菜品数量
        Integer count = dishMapper.countByIds(ids);
        if(count > 0){
            throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
        }
        //删除菜品基本信息
        dishMapper.deleteByIds(ids);

        //删除菜品口味信息
        dishFlavorMapper.deleteByDishIds(ids);
        //删除缓存
        clearCache("dish_*");
    }

    //根据id查询菜品信息
    @Override
    public DishVO selectById(Long id){
        //根据id查询菜品基本信息
        Dish dish = dishMapper.selectById(id);
        //根据id查询菜品口味信息
        List<DishFlavor> flavors = dishFlavorMapper.selectByDishId(id);
        DishVO dishVO = new DishVO();
        BeanUtils.copyProperties(dish,dishVO);
        dishVO.setFlavors(flavors);
        return dishVO;
    }

    //根据分类id查询菜品信息(不包含口味信息)
    @Override
    public List<Dish> selectByCategoryId(Long categoryId) {
        return dishMapper.selectByCategoryId(categoryId);
    }

    //根据分类id查询菜品信息(包含口味信息) 顾客端使用
    @Override
    public  List<DishVO> selectByCategoryIdWithFlavor(Long categoryId) {
        //先查询redis中是否有缓存菜品信息
        String key = "dish_" + categoryId;
        List<DishVO> list = (List<DishVO>) redisTemplate.opsForValue().get(key);
        if(list != null && !list.isEmpty()){
            //直接返回缓存中的菜品信息
            return list;
        }
        //缓存中没有菜品信息，查询mysql数据库并将菜品信息缓存到redis中,再返回
        list = dishMapper.selectByCategoryIdWithFlavor(categoryId);
        redisTemplate.opsForValue().set(key,list);
        return list;
    }
}
